package com.zym.exception;

import com.zym.enums.AckCode;
import com.zym.vo.R;
import lombok.extern.log4j.Log4j2;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import javax.naming.SizeLimitExceededException;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.List;

//捕获所有异常
@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * FileNotFoundException
     */
    @ExceptionHandler(value = FileNotFoundException.class)
    public R fileNotFoundException(FileNotFoundException foundException){
        String message = foundException.getMessage();
        R r = R.build(AckCode.FAIL);
        r.setMsg(message);
        return r;
    }
    /**
     * 处理文件上传大小超限制
     * @param e
     * @return
     */
    @ExceptionHandler(value = MultipartException.class)
    public R fileUploadExceptionHandler(MultipartException e, HttpServletResponse response) {
        if (e.getCause().getCause() instanceof FileSizeLimitExceededException){//单个文件大小超出限制抛出的异常
            log.error("message异常信息为=========》"+e.getMessage());
            log.error("cause异常信息为=========》"+e.getCause().getCause());
            return R.build(AckCode.FAIL,null,"单个上传文件大小不能超过20MB");


        }else if (e.getCause().getCause() instanceof SizeLimitExceededException){//总文件大小超出限制抛出的异常
            log.error("message异常信息为=========》"+e.getMessage());
            log.error("cause异常信息为=========》"+e.getCause().getCause());
            return R.build(AckCode.FAIL,null,"总上传文件大小不能超过200MB");

        }else {
            return R.build(AckCode.FAIL,null,"上传文件异常");
        }

    }

    @ExceptionHandler(value = BindException.class)
    public R bindingResult(BindException bindException){
        List<ObjectError> allErrors = bindException.getAllErrors();
        String msg = "";
        for (ObjectError allError : allErrors) {
              msg += allError.getDefaultMessage()+" & ";
        }

        R r = R.build(AckCode.FAIL);

         r.setMsg(msg);
         return r;
    }
    @ExceptionHandler(value = RuntimeException.class)
    public R runtimeException(RuntimeException runtimeException){
     return R.build(AckCode.FAIL);
    }
    @ExceptionHandler(value = MyException.class)
    public R MyException(MyException e){
        R r = R.build(AckCode.FAIL);
        r.setMsg(e.getMessage());
        return r;
    }

}
